<?php
/**
 * Model mapper for projects.
 *
 * @category PhpCilux
 * @package  PhpCilux
 */

/**
 * Model mapper for projects.
 *
 * @package PhpCilux
 */
class Model_ProjectMapper
{

    /**
     * Holds the build dir.
     *
     * @var string
     */
    protected $_buildDir;

    /**
     * Holds an instance of the class.
     *
     * @var array
     */
    protected $_projects;

    /**
     * Holds an instance of the class.
     *
     * @var Model_ProjectsMapper
     */
    protected static $_instance;

    /**
     * Singleton Getter.
     *
     * @return Model_ProjectsMapper
     */
    public static function &getInstance()
    {
        if (empty(self::$_instance)) {
            self::$_instance = new Model_ProjectMapper();
        }

        return self::$_instance;
    }

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->_buildDir = APPLICATION_PATH . DIRECTORY_SEPARATOR .
                            '..' . DIRECTORY_SEPARATOR .
                            'data' . DIRECTORY_SEPARATOR .
                            'build';
        $this->_buildDir = realpath($this->_buildDir) . DIRECTORY_SEPARATOR;
    }

    /**
     * Get a single skilltag.
     *
     * @param string $projectid Id of the skilltag.
     *
     * @return Tags_Model_Skilltags
     * @throws Exception Exception on can not find the project.
     */
    public function find($projectid)
    {
        if (isset($this->_projects[$projectid])) {
            return $this->_projects[$projectid];
        }

        if (is_dir($this->_buildDir . $projectid)) {
            $model = new Model_Project(array(
                'projectKey' => $projectid,
                'srcDir' => $this->_buildDir . $projectid . DIRECTORY_SEPARATOR . 'src'
            ));
            $this->_projects[$projectid] = $model;
            return $this->_projects[$projectid];
        }

        throw new Exception('Can not find project');
    }

    /**
     * Skilltags group by tag.
     *
     * @return array Array of Tags_Model_Skilltags
     */
    public function findAll()
    {
        $files = scandir($this->_buildDir);

        $this->_projects = array();
        foreach ($files as $file) {
            if (substr($file, 0, 1) !== '.' && is_dir($this->_buildDir . $file)) {
                $projectid = $file;
                $this->_projects[$projectid] = new Model_Project(array('projectKey' => $projectid));
            }
        }

        return $this->_projects;
    }

}